package com.NHL.single
{
	import com.NHL.interfaces.ICaller;
	import com.NHL.single.extra.GResponder;
	
	import flash.events.AsyncErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.NetConnection;
	import flash.net.ObjectEncoding;
	import flash.utils.Dictionary;
	
	import wingox.pool.ObjectPool;

	public class AmfCallPHP extends EventDispatcher implements ICaller
	{
		private static var _inst:AmfCallPHP;
		private var _sn:Number;
		private var _mapResponder:Dictionary = new Dictionary();
		private var _severTime:Number
		private var gateway:String = "http://127.0.0.1:8887/amfphp2/AmfPhp/Core/Gateway.php";
		private var _ncc:NetConnection;
		
		

		public static function getInstance():AmfCallPHP
		{
			return _inst||(_inst = new AmfCallPHP())
		}
		
		public function call(method:String,token:Object,result:Function,fault:Function= null,...params:Array):void
		{
			if(_ncc.uri != gateway)
			{
				_ncc.connect(gateway);
			}
			var responder :GResponder = ObjectPool.getPool(GResponder).borrowObject() as GResponder;
			responder.params = token;
			responder.resultFun = result;
			if(params[3])
			responder.statusFun = fault;
			responder.sn = ++_sn;
			responder.method = params[0];
			_ncc.call.apply(null,[method,responder].concat(params));
			_mapResponder[_sn]= responder;
		}
		
		 public function AmfCallPHP()
		{
			_ncc = new NetConnection();
			_ncc.objectEncoding = ObjectEncoding.AMF3;
			_ncc.addEventListener(AsyncErrorEvent.ASYNC_ERROR,onError,false,0,true);
			_ncc.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onError,false,0,true);
			_ncc.addEventListener(NetStatusEvent.NET_STATUS,onStatus,false,0,true);
			_ncc.addEventListener(IOErrorEvent.IO_ERROR,onError,false,0,true);
		}
		 
		 public function cancel(sn:Number):void
		 {
			 var rp:GResponder = _mapResponder[sn];
			 rp.method = null;
			 rp.resultFun = null;
			 rp.statusFun = null;
			 rp.params = null;
			 ObjectPool.getPool(GResponder).returnObject(rp);
			 delete _mapResponder[sn];
		 }
		 
		 private function onStatus(e:NetStatusEvent):void
		 {
			 switch(e.info.code)
			 {
				 
			 }
		 }
		
		private function onError(evt:Event):void
		{
			
		}
	}
}